有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java为什么是ServerSocket。setSocketFactory静态?

我正在尝试在Java中使用带有SSL的自定义SocketImpl。因此,我需要设置ServerSocket的socket工厂。我现在注意到它是静态的,这给我带来了一些麻烦,因为我想在每个ServerSocket实例中为它提供一些不同的参数。有人知道让它成为静态的理由吗?对我来说,这就像是一个不必要的约束,只会在你的应用程序中引入更多的全局状态

更新 对于为什么这是一个麻烦,似乎有一些困惑。这造成的问题是,它迫使我在整个应用程序中使用相同的工厂。如果我想在一个地方使用默认的SocketImpl,在另一个地方使用自定义的SocketImpl呢?要做到这一点,必须借助一些丑陋的反射黑客,因为工厂一旦设置好就无法改变。我也不能让我的工厂创建默认实现,因为SocksSocketImpl是包私有的


共 (6) 个答案

  1. # 1 楼答案

    SocketImpl is an abstract class that provides an interface for customizing socket implementations. Subclasses of SocketImpl are not intended to be explicitly instantiated. Instead, they are created by a SocketImplFactory. The motivation for this design is to allow you to change the default type of socket used by an entire application by calling Socket.setSocketImplFactory(), making it unnecessary to rewrite all of your networking code. Custom sockets are necessary for features such as SSL and firewall tunneling. Unfortunately, the global nature of setSocketImplFactory() is rather limiting, as it doesn't allow you to use multiple types of sockets within a single application. You can get around this by subclassing Socket and using the protected Socket(SocketImpl) constructor that was introduced in JDK 1.1.

    参考:http://www.devx.com/tips/Tip/26363

  2. # 2 楼答案

    对于mee来说,使用这个setter static似乎更容易使用,因为不需要ServerSocket实例,它允许您在不引用它的情况下设置套接字工厂。我认为使这个setter全球化实际上使它更容易实现,为什么对您来说很麻烦

  3. # 3 楼答案

    您希望非静态工厂知道如何神奇地实例化您的自定义类吗

  4. # 4 楼答案

    看看Constructor of ServerSocket

    If the application has specified a server socket factory, that factory's createSocketImpl method is called to create the actual socket implementation. Otherwise a "plain" socket is created.

    所以它必须是静态的,因为如果您希望在创建套接字的新实例时使用它,那么需要设置工厂

  5. # 5 楼答案

    这很恶心,但是您可以创建一个DelegatingSocketFactory,在调用它的人处查找调用堆栈,然后创建一个SocksSocketImpl(使用反射来排序可访问性),或者使用Ice4J。这算是一个反射黑客

  6. # 6 楼答案

    在我看来,这似乎是Factory Pattern的一个经典案例,在这个案例中,您提供了一个自定义工厂对象,其中的设置指示了如何创建某个类的实例。将操纵工厂的方法设置为静态是非常有意义的,因为工厂充当“元对象”,指导其他对象的创建

    从设计的角度来看,拥有每个实例的工厂根本没有意义。每个实例使用不同的工厂有什么意义?您是否计划从其他实例创建ServerSocket的实例?如果您想要不同的设置,每次只需提供不同的工厂即可